package com.tiantian.quanminxiu.fragment;


import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jakewharton.rxbinding.view.RxView;
import com.tiantian.quanminxiu.R;
import com.tiantian.quanminxiu.activity.MainActivity;
import com.tiantian.quanminxiu.adapter.AttentionListAdapter;
import com.tiantian.quanminxiu.model.RoomInfo;
import com.tiantian.quanminxiu.presenter.MainAttentionPresent;
import com.tiantian.quanminxiu.utils.APPUtils;
import com.tiantian.quanminxiu.utils.CommonEnum;
import com.tiantian.quanminxiu.utils.FragmentBase;
import com.tiantian.quanminxiu.utils.UserData;
import com.tiantian.quanminxiu.view.MainAttentionView;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import rx.functions.Action1;

/*
* 首页
* */
public class Fragment_Main_Attention extends FragmentBase implements MainAttentionView, BaseQuickAdapter.RequestLoadMoreListener{

    private MainAttentionPresent present;
    // 查询分页用到的参数
    private boolean boolPageLoading = false;            // 是否正在加载，防止重复加载
    private boolean boolPageEnd = false;                // 所有数据已加载完成
    private boolean P_Get = true;                       // 是否重新获取分页信息
    private int P_Current = 0;                          // 当前页数
    private int P_Total = 0;                            // 记录总条数
    private int P_MaxCode = 0;                          // MaxCode
    private int iDisplayLength = 15;                    // 数量（分页数量）

    private TextView txtLiveCount;
    private RecyclerView mRecyclerView;
    private View Header,rlAttentionNull;
    private AttentionListAdapter attentionAdapter;

    private MainActivity mainActivity;

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if(activity instanceof MainActivity){
            this.mainActivity = (MainActivity) activity;
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_attention, container, false);

        Init(view);
        InitView(view);
        present = new MainAttentionPresent();
        present.attachView(this);
        mSwipeRefresh.setOnRefreshListener(() -> {
            UserData.Reload.Fragment_Attention = true;
            PageInit();
        });

        UserData.Reload.Fragment_Attention = true;
        return view;
    }
    //endregion

    public void InitView(View view){
        rlAttentionNull =  view.findViewById(R.id.rlAttentionNull);
        mRecyclerView = (RecyclerView) view.findViewById(R.id.mRecyclerView);
        GridLayoutManager linearLayoutManager = new GridLayoutManager(thisContext,2);
        mRecyclerView.setLayoutManager(linearLayoutManager);
        Header = View.inflate(thisContext, R.layout.main_attention_header, null);
        txtLiveCount = (TextView) Header.findViewById(R.id.txtLiveCount);

        attentionAdapter = new AttentionListAdapter(thisActivity);
        attentionAdapter.openLoadAnimation();
        attentionAdapter.openLoadMore(iDisplayLength);
        attentionAdapter.setOnLoadMoreListener(this);
        View customLoading = thisActivity.getLayoutInflater().inflate(R.layout.recycleview_loading, (ViewGroup) mRecyclerView.getParent(), false);
        attentionAdapter.setLoadingView(customLoading);
        mRecyclerView.setAdapter(attentionAdapter);
        attentionAdapter.addHeaderView(Header);

        RxView.clicks(rlAttentionNull).map(View->rlAttentionNull).subscribe(OC_Button);
        RxView.clicks(view.findViewById(R.id.btnToLookLive)).map(View->view.findViewById(R.id.btnToLookLive)).subscribe(OC_Button);
    }

    private Action1<View> OC_Button = v->{
        switch (v.getId()){
            case R.id.rlAttentionNull:
            case R.id.btnToLookLive:
                if (mainActivity!=null) {
                    mainActivity.PageSwitch(CommonEnum.MainPageIndex.Hall);
                }
                break;
        }
    };

    //region PageInit()
    private void PageInit() {
        if (!UserData.Reload.Fragment_Attention) {
            return;
        }
        UserData.Reload.Fragment_Attention = false;
        attentionAdapter.getData().clear();
        attentionAdapter.setOnLoadMoreListener(this);
        P_Get = true;
        P_Current = 0;
        P_Total = 0;
        P_MaxCode = 0;
        boolPageEnd = false;
        PageData();
    }

    private void PageData(){
        if(!boolPageLoading){
            boolPageLoading = true;
            present.initAttentionList(UserData.Base.User_ID+"", iDisplayLength);
        }
    }

    @Override
    public void initAttentionList(JSONArray jsonArray) {
        P_Current++;
        List<RoomInfo> list = new ArrayList<RoomInfo>();
        rlAttentionNull.setVisibility(View.GONE);
        int liveNum = 0;
        for (int i=0;i<jsonArray.length();i++){
            JSONObject obj = jsonArray.optJSONObject(i);

            RoomInfo info = new RoomInfo();
            int User_ID = obj.optInt("User_ID");
            info.setRoomId(User_ID);
            info.setIsPlaying(obj.optInt("Live"));
            info.setIsMobile(obj.optInt("Live_IsMobile"));
            info.setImgUrl(APPUtils.createUserCover(User_ID));
            info.setAnchorName(obj.optString("NickName"));
            info.setAnchorid(User_ID);
            info.setHeat(obj.optInt("Hot_Value"));
            info.setTitle(obj.optString("RoomTitle"));
            info.setFans(obj.optInt("Fans"));
            info.setAnchorLevel(obj.optInt("Anchor_Level"));
            info.setUsreLevel(obj.optJSONObject("Level").optInt("Level"));
            if (info.getIsPlaying()==1){
                info.setLive_Mode(obj.optInt("Live_Mode"));
                liveNum++;
            }
            list.add(info);
        }
        if(attentionAdapter.getItemCount()==0){
            rlAttentionNull.setVisibility(View.VISIBLE);
        }
        if (jsonArray.length()<iDisplayLength)
        {
            attentionAdapter.setOnLoadMoreListener(null);
        }
        attentionAdapter.addData(list);
        attentionAdapter.notifyDataSetChanged();
        txtLiveCount.setText("正在直播("+liveNum+")");
        boolPageLoading = false;
    }

    @Override
    public void jumpLookRoom(int room_id) {

    }
    //endregion

    @Override
    public void onPause() {
        super.onPause();
    }

    @Override
    public void onResume() {
        super.onResume();
        PageInit();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        present.detachView();
    }

    @Override
    public void onLoadMoreRequested() {
        PageData();
    }
}